package com.fjl.filter;

import com.fjl.LogUtil;
import org.slf4j.MDC;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

public class AbpmFilter implements Filter {

    private static final String TRANSACTION_UUID_HEADER = "TRADE-UUID";
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 初始化配置（可选）
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        long l = System.currentTimeMillis();
        // 在请求处理前
        HttpServletRequest httpRequest = (HttpServletRequest) request;

        // 获取请求头中的 UUID
        String transactionUUID = httpRequest.getHeader(TRANSACTION_UUID_HEADER);

        // 如果请求头中没有 UUID，生成一个默认值
        if (transactionUUID == null || transactionUUID.isEmpty()) {
            transactionUUID = "generated-uuid-" + java.util.UUID.randomUUID().toString();
        }

        // 将 UUID 放入 MDC
        MDC.put("tradeUUID", transactionUUID);

        LogUtil.error("Filter is processing the request.");
        // 继续执行下一个过滤器或目标资源
        chain.doFilter(request, response);
        l = System.currentTimeMillis()-l;
        // 在响应返回前
        LogUtil.error("Filter is processing the response. time="+l+"ms");
    }

    @Override
    public void destroy() {
        // 销毁时的清理工作（可选）
    }
}
